package com.kpx.app.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.kpx.app.Application;
import com.kpx.app.R;
import com.kpx.app.base.ActivityBase;
import com.kpx.app.bean.SplashBean;
import com.kpx.app.bean.WelcomeBean;
import com.kpx.app.cache.FileCache;
import com.kpx.app.cache.SecondLevelCache;
import com.kpx.app.configs.Constants;
import com.kpx.app.http.HttpDataApi;
import com.kpx.app.http.HttpDataLoader;
import com.kpx.app.http.HttpDataReqUrl;
import com.kpx.app.http.HttpDataRequest;
import com.kpx.app.http.IPServFactory;
import com.kpx.app.http.ResObj;
import com.kpx.app.utils.MyHashMap;
import com.kpx.app.utils.StringUtil;
import com.kpx.app.utils.UniversualImageLoaderUtils;
import com.kpx.app.utils.UserInfoUtils;
import com.kpx.app.utils.datautils.FileUtils;
import com.kpx.app.utils.datautils.LogUtils;
import com.kpx.app.utils.dbutils.SpUtil;
import com.kpx.app.utils.systemutils.SystemConfigUtils;
import com.kpx.app.utils.uiutils.IntentUtil;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.kpx.app.wigdet.DialogFactoryImpl;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by Administrator on 2016/12/19.
 */
@RuntimePermissions
public class ActivitySplash extends ActivityBase {


    private static final String TAG = ActivitySplash.class.getName();

    @Override
    public void initview(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.fragment_splash);
        ButterKnife.bind(this);
    }

    private void getWelcomes() {
        MyHashMap map = new MyHashMap();
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                if (result.getCode() == 0) {
                    WelcomeBean b = (WelcomeBean) result.getData();
                    if (b != null) {
                        WelcomeBean btem = (WelcomeBean) FileCache.sharedInstance().get(Constants.KEY_WELCOME_BEAN);
                        String isfirst = (String) SpUtil.getString(Constants.KEY_ISFIRST);
                        if ((btem != null && btem.getVersion() < b.getVersion()) || (TextUtils.isEmpty(isfirst) || (!TextUtils.isEmpty(isfirst) && !isfirst.equals("1")))) {
                            SpUtil.putString(Constants.KEY_ISFIRST, "1");
                            IntentUtil.gotoActivityAndFinish(ActivitySplash.this, ActivityWelcome.class);
                        } else {
                            Intent intent = new Intent(ActivitySplash.this, ActivityMain.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            ActivitySplash.this.startActivity(intent);
                            ActivitySplash.this.finish();
                        }
                        FileCache.sharedInstance().put(Constants.KEY_WELCOME_BEAN, b);
                    }
                } else {
                    ToastUtil.getInstance().showToast(ActivitySplash.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                String isfirst = (String) SpUtil.getString(Constants.KEY_ISFIRST);
                if (TextUtils.isEmpty(isfirst) || (!TextUtils.isEmpty(isfirst) && !isfirst.equals("1"))) {
                    SpUtil.putString(Constants.KEY_ISFIRST, "1");
                    IntentUtil.gotoActivityAndFinish(ActivitySplash.this, ActivityWelcome.class);
                } else {
                    Intent intent = new Intent(ActivitySplash.this, ActivityMain.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    ActivitySplash.this.startActivity(intent);
                    ActivitySplash.this.finish();
                }
                ToastUtil.getInstance().showToast(ActivitySplash.this, error);
            }

        }, WelcomeBean.class, HttpDataRequest.TYPE_OBJECT).POST(HttpDataReqUrl.URL_POST_GET_WELCOME_LIST, true, map);
    }

    @Override
    public void initData() {
        mTopImage.setVisibility(View.VISIBLE);
        settingServerIpContainer.setVisibility(View.GONE);
        if (Constants.DEBUG) {
            String ipSrv = (String) SecondLevelCache.sharedInstance().get(Constants.KEY_CURR_SERVER_IP);
            if (TextUtils.isEmpty(ipSrv)) {
                mTopImage.setVisibility(View.GONE);
                settingServerIpContainer.setVisibility(View.VISIBLE);
                txtCurrentEnv.setText(getString(R.string.place_holder_curr_env));
                return;
            }
            DialogFactoryImpl.newInstance(this).showConfirmDialog(getString(R.string.cancel), getString(R.string.ok), "提醒", getString(R.string.alert_setting_server_ip), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                        case DialogInterface.BUTTON_NEGATIVE:
                            initSplashImg();
                            dialog.dismiss();
                            break;
                        case DialogInterface.BUTTON_POSITIVE:
                            mTopImage.setVisibility(View.GONE);
                            settingServerIpContainer.setVisibility(View.VISIBLE);
                            txtCurrentEnv.setText(IPServFactory.sharedInstance().currIPServ());
                            if (IPServFactory.sharedInstance().currIPServ().equals(IPServFactory.sharedInstance().externalProductEnv())) {
                                txtCurrentEnv.setText(getString(R.string.place_holder_curr_env).replace("#ipAddr", getString(R.string.external_product_env)));
                            } else if (IPServFactory.sharedInstance().currIPServ().equals(IPServFactory.sharedInstance().internalProductEnv())) {
                                txtCurrentEnv.setText(getString(R.string.place_holder_curr_env).replace("#ipAddr", getString(R.string.internal_product_env)));
                            } else {
                                String currIPServ = IPServFactory.sharedInstance().currIPServ();
                                txtCurrentEnv.setText(getString(R.string.place_holder_curr_env).replace("#ipAddr", currIPServ));
                            }
                            dialog.dismiss();
                            break;
                    }
                }
            });
        } else {
            showSplashImg();
        }
    }

    @Override
    public void onReceiver(Context context, Intent intent) {

    }

    private final int LOGOUT_REQUEST_FLAG = 1;
    private Handler fragmentSplashHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (ActivitySplash.this != null) {
                        getWelcomes();
                    }
                    break;
                case 1:
                    initSplashImg();
                    break;
            }
        }
    };
    /**
     * 闪屏页图片显示ImageView
     */
    @BindView(R.id.fragment_splash_top_image)
    public ImageView mTopImage;
    /**
     * 闪屏页设置IP地址View
     */
    @BindView(R.id.settingServerIpContainer)
    public View settingServerIpContainer;
    private static final String KEY_NEEDPERMISSION = "shouldShowRequestPermissionRationale";
    private static final String SHOW_WELCOME = "showWelcome";
    /**
     * 当前环境TextView
     */
    @BindView(R.id.txtCurrentEnv)
    public TextView txtCurrentEnv;
    /**
     * 手动输入IP编辑Container
     */
    @BindView(R.id.inputIpSerContainer)
    public View inputIpSerContainer;
    /**
     * 手动输入的IP地址EditText
     */
    @BindView(R.id.editServerIpEditText)
    public EditText editServerIpEditText;
    /**
     * 手动输入的IP地址的端口号EditText
     */
    @BindView(R.id.editServerPortEditText)
    public EditText editServerPortEditText;
    /**
     * 手动输入的工程名EditText
     */
    @BindView(R.id.editProjectNameEditText)
    public EditText editProjectNameEditText;


    @Override
    public void onResume() {
        super.onResume();
        if (!Constants.DEBUG) {
            toNeedPermission();
        }
    }

    @OnClick({R.id.switchToExternalPrdEvnTextView, R.id.switchToInternalPrdEvnTextView, R.id.inputInputAddrTextView, R.id.addIpBtn, R.id.skipSetting})
    public void onClickByButterKnife(View v) {
        switch (v.getId()) {
            case R.id.switchToExternalPrdEvnTextView: //切换到外部生产环境
                inputIpSerContainer.setVisibility(View.GONE);
                IPServFactory.sharedInstance().switchToExternalProductEnv();
                txtCurrentEnv.setText(getString(R.string.place_holder_curr_env).replace("#ipAddr", getString(R.string.external_product_env)));
                fragmentSplashHandler.sendEmptyMessageDelayed(1, 200);
                break;
            case R.id.switchToInternalPrdEvnTextView: //切换到内部生产环境
                inputIpSerContainer.setVisibility(View.GONE);
                IPServFactory.sharedInstance().switchToInternalProductEnv();
                txtCurrentEnv.setText(getString(R.string.place_holder_curr_env).replace("#ipAddr", getString(R.string.internal_product_env)));
                fragmentSplashHandler.sendEmptyMessageDelayed(1, 200);
                break;
            case R.id.inputInputAddrTextView: //手动输入
                if (inputIpSerContainer.getVisibility() != View.VISIBLE) {
                    inputIpSerContainer.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.addIpBtn: //手动输入设置按钮
                inputAddr();
                break;
            case R.id.skipSetting: //跳过设置
                fragmentSplashHandler.sendEmptyMessage(1);
                break;
        }
    }

    /**
     * 手动添加IP地址
     */
    private void inputAddr() {
        String ip = editServerIpEditText.getText().toString();
        int port = 0;
        String projectName = editProjectNameEditText.getText().toString();
        try {
            if (!TextUtils.isEmpty(editServerPortEditText.getText().toString())) {
                port = Integer.parseInt(editServerPortEditText.getText().toString());
            }
        } catch (Exception e) {
        }
        if (!TextUtils.isEmpty(ip) && port != 0 && !TextUtils.isEmpty(projectName)) {
            if (!StringUtil.isValidServIP(ip)) {
                ToastUtil.getInstance().showToast(ActivitySplash.this, R.string.tip_input_valid_ip);
                return;
            }
            if (!StringUtil.isValidServPort(port)) {
                ToastUtil.getInstance().showToast(ActivitySplash.this, R.string.tip_input_valid_port);
                return;
            }
        } else if (!TextUtils.isEmpty(ip) && port == 0 && TextUtils.isEmpty(projectName)) {
            if (TextUtils.isEmpty(ip) || !StringUtil.isValidDomainName(ip)) {
                ToastUtil.getInstance().showToast(ActivitySplash.this, R.string.tip_input_valid_domain);
                return;
            }
        } else {
            ToastUtil.getInstance().showToast(ActivitySplash.this, R.string.tip_input_valid);
        }
        String inputCurrentIp = ip + (port != 0 ? ":" + port : "") + (StringUtil.isValidDomainName(ip) ? "" : "/") + (!TextUtils.isEmpty(projectName) ? projectName : "");
        SecondLevelCache.sharedInstance().put(Constants.KEY_CURR_SERVER_IP, inputCurrentIp.trim());
        txtCurrentEnv.setText(getString(R.string.place_holder_curr_env).replace("#ipAddr", inputCurrentIp.trim()));
        inputIpSerContainer.setVisibility(View.GONE);
        hideSoftKeyboard(editServerPortEditText);
        fragmentSplashHandler.sendEmptyMessage(1);
    }

    private void initSplashImg() {
        mTopImage.setVisibility(View.VISIBLE);
        settingServerIpContainer.setVisibility(View.GONE);
        showSplashImg();
        toNeedPermission();
    }

    private void toNeedPermission() {
        if (SpUtil.getBoolean(SHOW_WELCOME, KEY_NEEDPERMISSION, false)) {
            DialogFactoryImpl.newInstance(ActivitySplash.this).showConfirmDialog(getString(R.string.cancel), getString(R.string.setting), getString(R.string.tip_grant_primary_permission_loc), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (DialogInterface.BUTTON_POSITIVE == which) {
                        try {
                            SpUtil.putBoolean(SHOW_WELCOME, KEY_NEEDPERMISSION, false);
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + Application.instance.getPackageName()));
                            startActivity(intent);
                        } catch (Exception e) {
                            LogUtils.e(TAG, e.toString());
                        }
                    } else {
                        dialog.dismiss();
                        ActivitySplash.this.finish();
                    }
                }
            });
            return;
        }
        ActivitySplashPermissionsDispatcher.getJPushPermissionWithCheck(this);
    }

    @NeedsPermission({"android.permission.READ_PHONE_STATE"
            , "android.permission.WRITE_EXTERNAL_STORAGE"
            , "android.permission.READ_EXTERNAL_STORAGE"
            , "android.permission.ACCESS_FINE_LOCATION"})
    public void getJPushPermission() {
        initJPush();
        if (null != ActivitySplash.this) {
            // 更新版本后,清除数据
            String key = "V" + SystemConfigUtils.getVersionCode();
            if (SpUtil.getBoolean(SHOW_WELCOME, key, true)) {
                SpUtil.putBoolean(SHOW_WELCOME, key, false);
                ImageLoader.getInstance().clearDiskCache();
                if (!TextUtils.isEmpty(SpUtil.getString(Constants.KEY_USER_TOKEN))) {
                    UserInfoUtils.loginOut();
                    return;
                }
            }
            fragmentSplashHandler.sendEmptyMessageDelayed(0, 3 * 1000);
        }
    }

    @OnShowRationale({"android.permission.READ_PHONE_STATE"
            , "android.permission.WRITE_EXTERNAL_STORAGE"
            , "android.permission.READ_EXTERNAL_STORAGE"
            , "android.permission.ACCESS_FINE_LOCATION"})
    public void showRationaleForJPush(final PermissionRequest request) {
        if (null == ActivitySplash.this) {
            return;
        }
        DialogFactoryImpl.newInstance(ActivitySplash.this).showConfirmDialog(getString(R.string.cancel), getString(R.string.setting), getString(R.string.alert_location_store_camera_audio_permission), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case DialogInterface.BUTTON_POSITIVE:
                        request.proceed();
                        break;
                    case DialogInterface.BUTTON_NEGATIVE:
                        if (null != ActivitySplash.this) {
                            dialog.dismiss();
                            ActivitySplash.this.finish();
                        }
                        break;
                }
            }
        });
    }

    @OnPermissionDenied({"android.permission.READ_PHONE_STATE"
            , "android.permission.WRITE_EXTERNAL_STORAGE"
            , "android.permission.READ_EXTERNAL_STORAGE"
            , "android.permission.ACCESS_FINE_LOCATION"})
    public void onJPushDenied() {
        if (null == ActivitySplash.this) {
            return;
        }
        SpUtil.putBoolean(SHOW_WELCOME, KEY_NEEDPERMISSION, true);
        ActivitySplash.this.finish();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // NOTE: delegate the permission handling to generated method
        ActivitySplashPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    /**
     * 初始化JPush
     */
    private void initJPush() {
        JPushInterface.setDebugMode(Constants.DEBUG);// 设置开启日志,发布时请关闭日志
        JPushInterface.init(ActivitySplash.this); // 初始化 JPush
    }

    private void showSplashImg() {
        SplashBean b = (SplashBean) FileCache.sharedInstance().get(Constants.KEY_SPLASH_BEAN);
        if (b != null) {
            ImageLoader.getInstance().displayImage(b.getValue(), mTopImage, UniversualImageLoaderUtils.getDisplayImageOptions());
        } else {
            mTopImage.setBackgroundResource(R.drawable.splash);
        }
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                if (result.getCode() == 0) {
                    SplashBean c = (SplashBean) result.getData();
                    if (c != null) {
                        FileCache.sharedInstance().put(Constants.KEY_SPLASH_BEAN, c);
                        ImageLoader.getInstance().displayImage(c.getValue(), mTopImage, UniversualImageLoaderUtils.getDisplayImageOptions());
                    }
                } else {
                    ToastUtil.getInstance().showToast(ActivitySplash.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                ToastUtil.getInstance().showToast(ActivitySplash.this, error);
            }

        }, SplashBean.class, HttpDataRequest.TYPE_OBJECT).POST(HttpDataReqUrl.URL_POST_GETLOAD_IMG, true, new MyHashMap());

    }

}
